<template>
    <div class="container">
        <el-page-header @back="goBack" content="站点价"></el-page-header>
        <!-- 分类 -->
        <div class="type-state e-m-t-45 e-m-b-30">
            <span class="e-p-l-30 e-p-r-30" v-for="(item, index) in statusArr" :key="index"
                :class="{ 'on': state == item.value }" @click="goPage(item.value)">{{ item.name }}</span>
        </div>

        <el-row type="flex" justify="space-between">
            <el-col :span="3">
                <el-button type="primary" icon="el-icon-plus" @click="createdGroup">新建站点价</el-button>
            </el-col>
            <el-col class="text-right">
                <el-form :inline="true"  class="nav-bar-form">
                    <el-form-item label="站点" prop="storeid">
                        <el-select 
                            v-model="storeid" 
                            placeholder="请选择站点"
                            filterable
                            remote
                            reserve-keyword
                            :remote-method="getStoreList"
                            @change="getList"
                            >
                            <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" :disabled="item.id == storeid?true:false">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary">查询</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>

        <!-- 站点价格列表 -->
        <el-table :data="tableData" stripe :border="true">
            <el-table-column label="指定站点" prop="storenames">
                <template slot-scope="scope">
                    <span>{{ scope.row.storenames }}</span>
                </template>
            </el-table-column>
            <el-table-column label="备注" prop="remarks">
                <template slot-scope="scope">
                    <span>{{ scope.row.remarks || '无' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="生效时间" prop="updatedatetime"></el-table-column>
            <el-table-column label="是否启用">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.state" @change="switchState($event, scope.row.id)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="text" size="small" @click="edit(scope.row.id)">编辑</el-button>
                    <el-button type="text" size="small" @click="setting(scope.row)">设置</el-button>
                    <el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
                    <el-button type="text" size="small" @click="downloadExcel(scope.row.id,`${scope.row.storenames}站点价`)">导出excel</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新建站点分组 -->
        <el-dialog :title="dialogType == 'add' ? '新建站点分组' : '编辑站点分组'" :visible.sync="dialogVisible" width="600px"
            @close="dialogVisible = false">
            <el-form ref="form" :model="form" >
                <el-form-item label="站点分组">
                    <el-select 
                        v-model="form.storeidArr" 
                        multiple
                        placeholder="请选择站点"
                        filterable
                        remote
                        reserve-keyword
                        :remote-method="getStoreList"
                        >
                        <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" :disabled="item.id == form.storeid?true:false">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="描述" prop="remarks">
                    <el-input v-model="form.remarks" type="textarea" :rows="3"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button v-if="dialogType == 'add'" type="primary" @click="submitCreatedGroup">添加</el-button>
                <el-button v-if="dialogType == 'edit'" type="primary" @click="submitEditGroup">修改</el-button>
            </span>
        </el-dialog>

        <!-- 设置 -->
        <el-dialog title="站点价设置" :visible.sync="settingDialogVisible" width="1200px"
            @close="settingDialogVisible = false">
            <el-descriptions class="e-m-b-30" title="" :column="2" border>
                <el-descriptions-item label="指定站点">
                    <div class="flex" style="align-items: center;">
                        <span class="e-p-l-5">{{ form.storenames }}</span>
                    </div>
                </el-descriptions-item>
                <el-descriptions-item label="生效时间">{{ form.updatedatetime }}</el-descriptions-item>
                <el-descriptions-item label="状态">{{ form.usestate }}</el-descriptions-item>
                <el-descriptions-item label="备注">{{ form.remarks }}</el-descriptions-item>
            </el-descriptions>
            <div class="e-m-b-30">
                <el-button type="primary" icon="el-icon-plus" @click="createdPriceType(form.id)">新建小类价格</el-button>
            </div>
            <el-table :data="settingList" stripe>
                <el-table-column label="小类名称" prop="product">
                    <template slot-scope="scope">
                        <span v-if="scope.row.product">{{ scope.row.product.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="默认站点价格" prop="defaultstore">
                    <template slot-scope="scope">
                        <span v-if="scope.row.defaultstore">{{ scope.row.defaultstore.price }}</span>
                        <span v-if="scope.row.defaultstore.edit">(允许改价)</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="站点回收用户价格" prop="storeuser">
                    <template slot-scope="scope">
                        <span v-if="scope.row.storeuser">{{ scope.row.storeuser.price }}</span>
                        <span v-if="scope.row.storeuser.edit">(允许改价)</span>
                    </template>
                </el-table-column> -->
                <el-table-column label="站点回收价格" prop="fit">
                    <template slot-scope="scope">
                        <span v-if="scope.row.fit">{{ scope.row.fit.price }}</span>
                        <span v-if="scope.row.fit.edit">(允许改价)</span>
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" prop="updatedatetime">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="editPrice(scope.row)">编辑</el-button>
                        <el-button type="text" size="small" @click="delPrice(form.id, scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="settingDialogVisible = false">取消</el-button>
                <!-- <el-button type="primary">保存</el-button> -->
            </span>
        </el-dialog>
        <!-- 新建或编辑小类价格 -->
        <el-dialog :title="editDialogType == 'add' ? '新建小类价格' : `编辑${editPriceForm.product.name}价格`" :visible.sync="editDialogVisible" width="600px" @close="editDialogVisible = false">
            <el-form ref="form" :model="editPriceForm"  label-width="160px">
                <el-form-item label="选择品类" v-if="editDialogType == 'add'">
                    <!-- <el-cascader ref="chooseType" v-model="editPriceForm.productId" placeholder="请选择调整后的品类" separator="-" @change="selectSmallType" filterable
                        :props="{
                            lazy: true,
                            checkStrictly: true,  // 新增这个属性
                            lazyLoad: loadSmallType,
                            label: 'name',
                            value: 'id',
                            emitPath: false       // 新增这个属性
                        }" style="width: 100%;margin-right: 20px"></el-cascader> -->

                        <selectProduct v-model="editPriceForm.productId" @select="chooseProduct" class="e-w-300"></selectProduct>
                </el-form-item>
                <!-- <el-form-item label="站点回收用户价格设置" prop="storeuser">
					<div class="flex e-m-b-15" style="align-items: center;">
						<el-input 
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="editPriceForm.storeuser.price">
							<template slot="prepend">价格</template>
						</el-input>
						<el-switch v-model="editPriceForm.storeuser.edit" active-text="允许修改"></el-switch>
					</div>
                    <div class="flex e-m-b-15" style="align-items: center;" v-if="editPriceForm.storeuser.edit == true">
                        <el-input 
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="editPriceForm.storeuser.minprice">
							<template slot="prepend">允许修改最低价格</template>
						</el-input>
                    </div>
                    <div class="flex" style="align-items: center;" v-if="editPriceForm.storeuser.edit == true">
                        <el-input 
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="editPriceForm.storeuser.highprice">
							<template slot="prepend">允许修改最高价格</template>
						</el-input>
                    </div>
				</el-form-item> -->
                <el-form-item label="价格设置" prop="fit">
					<div class="flex e-m-b-15" style="align-items: center;">
						<el-input 
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="editPriceForm.fit.price">
							<template slot="prepend">价格</template>
						</el-input>
						<el-switch v-model="editPriceForm.fit.edit" active-text="允许修改"></el-switch>
					</div>
                    <div class="flex e-m-b-15" style="align-items: center;" v-if="editPriceForm.fit.edit == true">
                        <el-input 
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="editPriceForm.fit.minprice">
							<template slot="prepend">允许修改最低价格</template>
						</el-input>
                    </div>
                    <div class="flex" style="align-items: center;"  v-if="editPriceForm.fit.edit == true">
                        <el-input 
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="editPriceForm.fit.highprice">
							<template slot="prepend">允许修改最高价格</template>
						</el-input>
                    </div>
				</el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="sumbitCreatedPriceType">保存</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    layout: 'admin',
    head() {
        return {
            title: '站点价' 
        }
    },
    data() {
        return {
            loading: false,
            pageIndex: 1,
            pageSize: 999,
            total: 0,
            key: '',
            tableData: [],
            statusArr: [
                {
                    name: '默认价格',
                    value: 1
                },
                {
                    name: '上门价',
                    value: 2
                },
                {
                    name: '站点价',
                    value: 3
                },
                {
                    name: '客户组价',
                    value: 4
                }
            ],
            state: 3,
            storeList: [],
            storeid: null,
            dialogType: 'add',
            dialogVisible: false,
            form:{
                storeid: null,
                storeNames: '',
                remarks: '',
                storeidArr: []
            },

            settingDialogVisible: false,
            settingList: [],
            // 新建或编辑小类价格
            editDialogType: 'add',
            editDialogVisible: false,
            editPriceForm: {
                priceid: 0, //价格ID
                productId: 0, //废品小类ID
                storeuser: { //站点回收用户价格
                    edit: true, //是否允许修改
                    price: 0, //价格
                    minprice: 0, //允许修改最低价格
                    highprice: 0 //允许修改价格
                },
                fit: { //散客回收价格
                    edit: true, //是否允许修改
                    price: 0, //价格
                    minprice: 0, //允许修改最低价格
                    highprice: 0 //允许修改价格
                }
            },
            typeId: 0
        }
    },
    mounted() {
        this.getList()
        this.getStoreList()
    },
    methods: {
        // 跳转页面
        goPage(value) {
            switch (value) {
                case 1:
                    this.$router.push(`/price/default`)
                    break
                case 2:
                    this.$router.push(`/price/onsite`)
                    break
                case 3:
                    this.$router.push(`/price/store`)
                    break
                case 4:
                    this.$router.push(`/price/enterprise`)
                    break
            }
        },
        // 返回上一页
        goBack() {
            this.$router.go(-1)
        },
        // 获取站点价列表
        getList(){
            this.$axios.post('/Waste/StorePrice/List', {
                "pageIndex": 1,
                "pageSize": 999,
            }).then((res) => {
                let datas = res.rows
                datas.forEach((item) => {
                    if (item.usestate == '已启用') {
                        item.state = true
                    } else {
                        item.state = false
                    }
                })
                this.tableData = datas
            })
        },
        getStoreList(key = ''){ //获取站点列表
            this.$axios.post('/Select/StoreList',{
                "PageIndex": 1,
                "PageSize": 20,
                "Key": key
            }).then((res) => {
                console.log(res)
                this.storeList = res.rows
            })
        },
        // loadSmallType(node, resolve) { //加载品类
        //     const { level, value: pid } = node;
    
        //     // 第一级加载类型时自动记录ID
        //     if (level === 0) {
        //         this.$axios.get('/Waste/Type/List').then((res) => {
        //             const nodes = res.map(c => ({
        //                 id: c.id,
        //                 name: c.name,
        //                 // 添加原始数据用于后续获取
        //                 rawData: c 
        //             }));
        //             resolve(nodes);
        //         });
        //         return;
        //     }

        //     // 当选择第一级时记录类型ID
        //     if (level === 1) {
        //         this.typeId = node.data.rawData.id; // 从节点原始数据获取
        //     }

        //     // 后续请求统一使用已记录的类型ID
        //     const params = {
        //         pid: pid,
        //         typeId: this.typeId
        //     };

        //     if (level === 1) {
        //         delete params.pid;
        //     }

        //     this.$axios.get('/Waste/product/List', { params })
        //         .then((res) => {
        //             const nodes = res.map(c => ({
        //                 id: c.id,
        //                 name: c.name,
        //                 leaf: c.hasChildren === false,
        //                 rawData: c // 继续携带原始数据
        //             }));
        //             resolve(nodes);
        //         });
        // },
        // selectSmallType(v) { //选择品类
        //     // 通过节点链获取完整分类信息
        //     const nodes = this.$refs.chooseType.getCheckedNodes()[0];
        //     let current = nodes;
            
        //     // 向上遍历找到类型ID
        //     while(current.level > 1){
        //         current = current.parent
        //     }
            
        //     this.typeId = current.data.rawData.id;
        //     this.editPriceForm.productId = nodes.value;
        // },
        chooseProduct(obj){
            console.log('选择品类',obj)
            this.typeId  = obj.typeid
            this.editPriceForm.productId = obj.id
        },
        // 
        createdGroup(){
            this.dialogType = 'add'
            this.dialogVisible = true
            this.form = {
                storeid: null,
                remarks: ''
            }
        },
        // 确认提交站点分组
        submitCreatedGroup() {
            this.$axios.post('/Waste/StorePrice/Create', {
                // "storeid": [this.form.storeid],
                "storeid": this.form.storeidArr, //站点ID"
                "remarks": this.form.remarks
            }).then((res) => {
                this.$message.success(res.msg);
                this.dialogVisible = false;
                this.getList()
            })
        },
        submitEditGroup() {
            this.$axios.post('/Waste/StorePrice/Edit', {
                "id": this.form.id,
                "storeId": this.form.storeidArr,
                "remarks": this.form.remarks
            }).then((res) => {
                this.$message.success(res.msg);
                this.dialogVisible = false;
                this.getList()
            })
        },
        //修改状态
        switchState(event, id) {
            this.$axios.get('/Waste/StorePrice/SetState', {
                params: {
                    id: id,
                    state: event ? '已启用' : '已冻结'
                }
            }).then((res) => {
                if (res.status == 0) {
                    this.$message.success(res.msg);
                } else {
                    this.$message.error(res.msg);
                }
            }).catch((err) => {
                this.getList()
            })
        },
        // 编辑分组
        edit(id) {
            this.$axios.get('/Waste/StorePrice/Detail?id=' + id).then((res) => {
                console.log(res)
                this.form.id = res.id
                this.form.storeid = res.stores[0].id
                this.form.storeNames = res.storeNames
                this.form.remarks = res.remarks

                this.form.storeidArr = []
                res.stores.forEach((item) => {
                    this.form.storeidArr.push(item.id)
                })

                this.dialogType = 'edit'
                this.dialogVisible = true

                this.$forceUpdate()
            })
        },
        // 删除分类
        del(id) {
            this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get('/Waste/StorePrice/Del?id=' + id).then((res) => {
                    this.$message.success(res.msg);
                    this.getList()
                })
            })
        },
        // 设置 
        setting(obj) {
            this.form = obj
            this.$axios.get('/Waste/StorePriceDetail/List?priceId=' + obj.id).then((res) => {
                this.settingList = res
                this.settingDialogVisible = true
            })
        },
        // 
        createdPriceType(priceid){
            console.log('priceid',priceid)
            this.editDialogType = 'add'
            this.editPriceForm= {
                priceid: priceid,
                productId: 0,
                storeuser: {
                    edit: true,
                    price: 0,
                    minprice: 0,
                    highprice: 0
                },
                fit: {
                    edit: true,
                    price: 0,
                    minprice: 0,
                    highprice: 0
                }
            }
            this.editDialogVisible = true
        },
        // 创建或修改站点回收用户价格
        sumbitCreatedPriceType(){
            let params = {
                priceid: this.editPriceForm.priceid,
                productId: this.editPriceForm.productId,
                fit: {
                    edit: this.editPriceForm.fit.edit,
                    price: this.editPriceForm.fit.price,
                    minprice: this.editPriceForm.fit.minprice,
                    highprice: this.editPriceForm.fit.highprice
                },
                storeuser: { //站点回收用户价格,暂时与散客价一样
                    edit: this.editPriceForm.fit.edit,
                    price: this.editPriceForm.fit.price,
                    minprice: this.editPriceForm.fit.minprice,
                    highprice: this.editPriceForm.fit.highprice
                },
            }
            this.$axios.post('/Waste/StorePriceDetail/Save',params).then((res)=>{
                this.$message.success(res.msg);
                this.editDialogVisible = false;
                this.$axios.get('/Waste/StorePriceDetail/List?priceId=' + params.priceid).then((res) => {
                    this.settingList = res
                })
            })
        },
        // 删除地区分组价格
        delPrice(pid, id) {
            this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get('/Waste/StorePriceDetail/Del?id=' + id).then((res) => {
                    this.$message.success(res.msg);
                    this.$axios.get('/Waste/StorePriceDetail/List?priceId=' + pid).then((res) => {
                        this.settingList = res
                    })
                })
            })
        },
        // 编辑地区分组价格
        editPrice(form) {
            console.log('编辑地区分组价格',form)
            this.editPriceForm = form
            this.editPriceForm.productId = form.product.id
            this.editDialogType = 'edit'
            this.editDialogVisible = true
        },
        downloadExcel(id,downloadFileName) {
            //导出
            let param = {
                id: id,
                downloadFileName: downloadFileName
            }
            this.$axios.post('/Waste/StorePrice/Download', 
                param,
                {
                    responseType: 'blob'
                }
            ).then((res)=>{
                let content = res;
                let fileName = `${downloadFileName}.xls`
                this.utils.saveAndExport(content, fileName)
            })
        }
    }
}
</script>